<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 点位详情 -->
    <a-spin :spinning="loading" id="base-breadcrumb" style="position: relative">
      <!-- 基础信息 -->
      <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
        <a-card :bordered="false">
          <title-name title="基础信息"></title-name>
          <custom-form
            :form="form"
            :formList="baseInfo"
            :rules="rules"
            :editModel="['C', 'E', 'V', 'R'][editModel]"
          ></custom-form>
        </a-card>
        <!-- 点位信息 -->
        <a-card :bordered="false">
          <title-name title="点位信息"></title-name>
          <custom-form
            :form="form"
            :formList="pointInfo"
            :rules="rules"
            :editModel="['C', 'E', 'V', 'R'][editModel]"
          ></custom-form>
        </a-card>
      </a-form-model>
      <!-- 表格 -->
      <a-card :bordered="false" style="margin-bottom: 80px">
        <title-name title="检查项信息"></title-name>
        <a-button
          v-if="editModel != 2"
          :disabled="disabled"
          type="primary"
          icon="plus"
          class="mb12"
          @click="visible = true"
          >添加检查项</a-button
        >
        <div>
          <s-table
            ref="table"
            tableLayout="fixed"
            size="default"
            rowKey="id"
            :columns="columns"
            :data="loadData"
            :alert="true"
            :showPagination="false"
          >
            <template slot="index" slot-scope="text, record, index">
              {{ index + 1 }}
            </template>
            <!-- 表格行操作栏 -->
            <template slot="action" slot-scope="text, record, index">
              <a
                v-btnPermission="
                [
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_032_reci_10'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_032_reci_10'
                      }
              ]"
                v-if="
                  !record.isDel && record.status == '1' && (editModel == 3 || (editModel == 1 && form.isRestructure))
                "
                @click="
                  forms = record
                  visibleTwo = true
                "
                >重构</a
              >
              <a
                v-if="
                  editModel == 1 &&
                  ((form.isRestructure && record.isNew && !record.isDel) ||
                    (!form.isRestructure && record.isRestructure == 'false'))
                "
                :class="{ del_btn: record.status === '1' }"
                v-btnPermission="[
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_032_sto_08'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_032_sto_08'
                      }
              ]"
                @click="handleRemove(record)"
                >{{ record.status === '0' ? '启用' : '停用' }}</a
              >
              <a
                class="del_btn"
                v-btnPermission="
                [
                      {
                        ident: 'prma_seex',
                        code: 'seex_qm_032_del_07'
                      },
                      {
                        ident: 'prma_buco',
                        code: 'buco_qm_032_del_07'
                      }
              ]"
                v-if="record.isDel"
                type="danger"
                @click="handleDelete(index)"
                >删除</a
              >
            </template>
          </s-table>
        </div>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      class="btn_box page-btn-right-top"
      style="position: fixed; bottom: 0; right: 50px; height: 50px; display: flex; align-items: center"
    >
      <a-button :loading="loading" v-if="editModel != 2" type="primary" class="button_right" @click="handleSubmit"
        >提交</a-button
      >
      <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
    </div>
    <!-- 添加检查项表单弹窗 -->
    <DialogCheckItem
      ref="dialogCheckItem"
      :editModel="editModel"
      :loadDatas="loadDatas"
      :visible.sync="visible"
      :api="api"
      :form="{ whether: false, projectId: form.projectId, branchCompanyId: form.branchCompanyId }"
      @confirm="submitForm"
    />
    <!-- 重构表单弹窗 -->
    <DialogEdit :visible.sync="visibleTwo" editModel="3" :form="forms" @refresh="handleRefactor" />
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import DialogCheckItem from '@/views/quality/measuredAmount/pointListMaintenance/dialogEdit' // 添加检查项
import DialogEdit from '../components/DialogEdit' // 重构表单弹窗
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector'
import { pointList, checkItem, pointListCheckItem } from '@/api/quality/reality' // 实测实量api

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    DialogCheckItem,
    DialogEdit
  },
  computed: {
    columns() {
      const columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: '80px',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '检查项名称',
          dataIndex: 'checkItemName',
          ellipsis: true,
          width: '230px'
        },
        {
          title: '判定类型',
          dataIndex: 'judgmentType',
          ellipsis: true,
          width: '130px'
        },
        // {
        //   title: '点位检测名称',
        //   dataIndex: 'implementationTime',
        //   width: '130px',
        // },
        {
          title: '最小偏差值',
          dataIndex: 'negativeDeviation',
          width: '130px',
          customRender(e, record) {
            return record.judgmentTypeCode !== '2' ? e : ''
          }
        },
        {
          title: '标准值',
          dataIndex: 'standardValue',
          width: '130px',
          customRender(e, record) {
            return record.judgmentTypeCode === '2' ? '合格/不合格' : e
          }
        },
        {
          title: '最大偏差值',
          dataIndex: 'positiveDeviation',
          width: '130px',
          customRender(e, record) {
            return record.judgmentTypeCode !== '2' ? e : ''
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '130px',
          customRender(e) {
            return ['不可用', '可用'][e] || ''
          }
        }
      ]
      if (this.editModel != 2) {
        columns.push({
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        })
      }
      return columns
    },
    disabled() {
      let disabled = false
      if (this.editModel == 3) {
        let level = this.level
        // 登陆人组织为分公司，且分公司为空则添加按钮禁用
        if (level === '1' && !this.form.branchCompanyId) {
          disabled = true
          // 登陆人组织为项目，且项目为空则添加按钮禁用
        } else if (level === '2' && !this.form.projectId) {
          disabled = true
        }
      }
      return disabled
    },
    // 检查项api
    api() {
      return checkItem
    },
    // 基础信息表单列表
    baseInfo() {
      return [
        {
          type: Selector,
          keyName: 'pointLevelCode',
          viewName: 'pointLevelName',
          disabled: true,
          label: '点位等级',
          attrs: {
            selectType: '15',
            valueName: 'code'
          }
        },
        {
          type: SelectSubCompany,
          keyName: 'branchCompanyId',
          disabled: this.editModel == 3 && this.level == 0,
          hidden: !this.init && this.editModel == 3 ? this.level == 0 : this.form.pointLevelCode == 0,
          viewName: 'branchCompanyName',
          label: '分公司',
          attrs: {
            autoSelected: this.editModel == 0 || this.editModel == 3
          }
        },
        {
          type: SelectProject,
          keyName: 'projectId',
          disabled: this.editModel == 3 && this.level != 2,
          hidden: this.editModel == 3 ? this.level != 2 : this.form.pointLevelCode != 2,
          viewName: 'projectName',
          label: '项目部',
          attrs: {
            autoSelected: this.editModel == 0 || this.editModel == 3,
            isClear: this.editModel == 0,
            isEdit: this.editModel != 0
          }
        }
      ]
    },
    // 点位表单列表
    pointInfo() {
      return [
        {
          type: 'a-input',
          keyName: 'pointName',
          disabled: this.editModel == 3,
          label: '点位名称'
        },
        {
          type: 'BaseTextarea',
          keyName: 'pointDescription',
          disabled: this.editModel == 3,
          label: '点位描述',
          span: 24
          // attrs: {
          //   type: 'textarea',
          // },
        }
      ]
    }
  },
  data() {
    return {
      forms: {}, // 重构弹窗表单
      visible: false, // 添加检查项弹窗控件
      visibleTwo: false, // 重构弹窗控件
      // 查询参数
      queryParam: {},
      // 盒子高度
      boxHeight: 0,
      loading: false,
      editModel: 0,
      id: '',
      level: sessionStorage.getItem('currentLevel'),
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.editModel != 0) {
          this.loading = true
          return pointList
            .getDetail({
              id: this.id
            })
            .then((res) => {
              this.loading = false
              if (res.code === 200) {
                this.init = true
                let datas = cloneDeep(res)
                if (this.form.branchCompanyId) {
                  res.data.branchCompanyId = this.form.branchCompanyId
                }
                if (this.form.projectId) {
                  res.data.projectId = this.form.projectId
                }
                this.form = res.data
                // this.form = res.data
                // this.code = res.data.pointLevelCode
                datas.data = res.data.checkItems // 列表对象
                this.loadDatas = datas.data
                return datas
              }
            })
            .catch(() => {
              this.loading = false
            })
        }
        return Promise.reject()
      },
      form: {},
      loadDatas: [],
      rules: {
        pointLevelCode: [{ required: true, message: '请选择点位等级', trigger: 'change' }],
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        pointName: [{ required: true, whitespace: true, message: '请输入点位名称', trigger: 'change' }]
        // subItemId: [{ required: true, whitespace:true,message: '请输入点位名称', trigger: 'change' }],
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['点位新增', '点位编辑', '点位查看', '点位重构'][this.editModel]
    // 添加默认组织级别
    this.$set(this.form, 'pointLevelCode', this.level)
  },
  methods: {
    /**
     * @description: 重构计划项
     * @param {*} data：计划项业务对象
     */
    handleRefactor(data) {
      if (this.$refs.table) {
        // 找出当前索引值
        let index = this.$refs.table.localDataSource.findIndex((i) => i.id == this.forms.id)
        // 添加剂新计划项
        this.$set(this.$refs.table.localDataSource, index, data)
      }
    },
    /**
     * 删除当前项
     */
    handleDelete(index) {
      this.$confirm({
        title: '温馨提示',
        content: '确认删除？',
        onOk: () => {
          this.$refs.table.localDataSource.splice(index, 1)
          this.loadDatas = this.$refs.table.localDataSource
        }
      })
    },
    /**
     * 停启用
     */
    handleRemove(e) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: `确认${e.status === '0' ? '启用' : '停用'}？`,
        onOk() {
          return pointListCheckItem.switchStatus({ pointId: that.form.id, checkItemId: e.id }).then((res) => {
            if (res.code === 200 || res.data.code === 200) {
              that.$message.success(`${e.status === '0' ? '启用' : '停用'}成功！`)
              e.status = e.status === '0' ? '1' : '0'
              // that.$refs.table.loadData()
            }
          })
        }
      })
    },
    /**
     * 新增检查项
     */
    submitForm(e) {
      e.forEach((t) => {
        t.isDel = true
        // 有重构标识时添加重构的新增标识
        if (this.form.isRestructure) {
          t.isNew = true
        }
      })
      // 是否已存在于列表
      if (this.$refs.table.localDataSource.some((item) => e.map((i) => i.id).includes(item.id))) {
        this.$message.warning('请勿重复添加检查项！')
        return
      } else {
        this.$refs.table.localDataSource = this.$refs.table.localDataSource.concat(e)
        this.loadDatas = this.$refs.table.localDataSource
      }
      this.$nextTick(this.$refs.dialogCheckItem?.$refs.table?.loadData)
      // this.visible = false
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      let name = ['create', 'update', '', 'refactor'][that.editModel] // 根据操作切换url地址
      that.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (that.$refs.table.localDataSource.length === 0) {
            that.$message.warning('请添加检查项！')
            return
          }
          // 配置请求参数
          let form = Object.assign({}, that.form, {
            checkItemInfo: that.$refs.table.localDataSource,
            subItemId: that.subItemId
          })
          // that.id && (that.form.id = that.id)
          that.loading = true
          pointList[name](form)
            .then((res) => {
              if (res.code === 200 || res.data.code === 200) {
                that.loading = false
                that.$message.success(['添加', '编辑', '', '重构'][that.editModel] + '成功！')
                that.$multiTab.close()
              }
            })
            .catch((res) => {
              // that.$message.warning(['添加', '编辑'][that.editModel] + '失败')
              that.loading = false
            })
        } else {
          that.$message.warning('表单不完整')
        }
      })
    }
  }
}
</script>
<style scoped>
.text_name {
  margin-top: -3px;
}
</style>
